<template>
  <div class="gi_page">
    <a-spin :loading="loading">
      <a-form
        ref="formRef"
        :model="form"
        auto-label-width
        label-align="left"
        :layout="width >= 500 ? 'horizontal' : 'vertical'"
        :disabled="!isUpdate"
        scroll-to-first-error
        class="form"
      >
        <a-form-item
          field="dbConn.driverName" label="数据库" tooltip="演示时可以使用sqlite，正式环境建议使用MYSQL" :rules="[
            {
              required: true,
              message: `数据库源必须设置`,
            },
          ]"
        >
          <a-select v-model="form.dbConn.driverName" placeholder="请选择">
            <a-option value="MYSQL">MYSQL</a-option>
            <a-option value="SQLite" disabled>SQLite</a-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.host" label="主机地址" :rules="[
            {
              required: true,
              message: `请输入主机地址`,
            },
          ]"
        >
          <a-input v-model="form.dbConn.host" placeholder="请输入主机地址" />
        </a-form-item>
        <a-form-item
          v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.dbname" label="数据库名" :rules="[
            {
              required: true,
              message: `数据库名必填`,
            },
          ]"
        >
          <a-input v-model="form.dbConn.dbname" placeholder="请输入数据库名称" />
        </a-form-item>
        <a-form-item
          v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.port" label="端口号" :rules="[
            {
              required: true,
              message: `端口号必填`,
            },
          ]"
        >
          <a-input-number v-model="form.dbConn.port" placeholder="请输入端口号" />
        </a-form-item>
        <a-form-item
          v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.userName" label="用户" :rules="[
            {
              required: true,
              message: `用户必填`,
            },
          ]"
        >
          <a-input v-model="form.dbConn.userName" placeholder="请输入用户名">
            <template #prefix>
              <IconUser />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item
          v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.password" label="密码" :rules="[
            {
              required: true,
              message: `密码必填`,
            },
          ]"
        >
          <a-input-password v-model="form.dbConn.password" autocomplete="off" placeholder="请输入密码" />
        </a-form-item>
        <a-form-item v-if="form.dbConn.driverName === 'MYSQL'" field="dbConn.timeout" label="超时时间">
          <a-input-number v-model="form.dbConn.timeout" placeholder="超时设置" />
        </a-form-item>
        <a-form-item field="isAutoMigrate" tooltip="首次创建表时，自动创建表结构，关闭后提高启动速度" label="自动建表">
          <a-switch v-model="form.dbConn.isAutoMigrate" type="round" />
        </a-form-item>
        <a-form-item
          field="redis.addr"
          label="Redis地址"
          hide-asterisk
        >
          <a-input v-model.trim="form.redis.addr" />
        </a-form-item>
        <a-form-item
          field="redis.redis_password"
          label="Redis密码"
          hide-asterisk
          :rules="[
            {
              required: true,
              message: `密码必填`,
            },
          ]"
        >
          <a-input-password v-model.trim="form.redis.redis_password" autocomplete="off" />
        </a-form-item>
        <a-form-item
          label="端口"
          field="redis.db"
          help="reids服务器连接端口"
          hide-asterisk
          :rules="[
            {
              required: true,
              message: `数据库端口必填`,
            },
          ]"
        >
          <a-input-number v-model="form.redis.db" :min="0" />
        </a-form-item>

        <a-space style="margin-bottom: 16px">
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" type="primary" @click="onUpdate">
            <template #icon><icon-edit /></template>修改
          </a-button>
          <a-button v-if="!isUpdate" v-permission="['system:mailConfig:update']" @click="onResetValue">
            <template #icon><icon-undo /></template>恢复默认
          </a-button>
          <a-button v-if="isUpdate" type="primary" @click="handleSave">
            <template #icon><icon-save /></template>保存
          </a-button>
          <a-button v-if="isUpdate" @click="reset">
            <template #icon><icon-refresh /></template>重置
          </a-button>
          <a-button v-if="isUpdate" @click="handleCancel">
            <template #icon><icon-undo /></template>取消
          </a-button>
        </a-space>
      </a-form>
    </a-spin>
    <a-alert v-if="isAlert" :type="alerttype">{{ alertText }}</a-alert>
  </div>
</template>

<script setup lang="ts">
import { useWindowSize } from '@vueuse/core'
import { type FormInstance, Message, Modal } from '@arco-design/web-vue'
import {
  CheckHealth,
  GetDataSource,
  UpdateDataSource,
} from '@/apis/plugin/datasource'
import { useResetReactive } from '@/hooks'
import { encryptByRsa } from '@/utils/encrypt'

defineOptions({ name: 'SystemMailConfig' })
const { width } = useWindowSize()
const loading = ref<boolean>(false)
const formRef = ref<FormInstance>()
const [form] = useResetReactive({
  id: '',
  version: '',
  name: '',
  dbConn: {
    driverName: '',
    userName: '',
    host: '',
    port: '',
    dbname: '',
    timeout: 0,
    password: '',
    isAutoMigrate: true,
  },
  redis: {
    addr: '',
    db: 0,
    redis_password: '',
  },
})
const isAlert = ref(false)
const alerttype = ref('success')
const alertText = ref('')
// 重置
const reset = () => {
  formRef.value?.resetFields()
}

const isUpdate = ref(false)
// 修改
const onUpdate = () => {
  isUpdate.value = true
}

// 取消
const handleCancel = () => {
  reset()
  isUpdate.value = false
}

// 查询列表数据
const getDataList = async () => {
  loading.value = true
  const { data } = await GetDataSource('caipu-site')
  Object.assign(form, data.jsonData)
  form.id = data.id
  form.version = data.version
  form.name = data.name
  loading.value = false
}

// 保存
const handleSave = async () => {
  const isInvalid = await formRef.value?.validate()
  if (isInvalid) return false
  const formData = ref({
    id: form.id,
    name: form.name,
    version: form.version,
    remark: 'go-caipu配置',
    securejsonData: '',
    jsondata: {
      dbConn: {
        driverName: form.dbConn.driverName,
        userName: form.dbConn.userName,
        host: form.dbConn.host,
        port: form.dbConn.port,
        dbname: form.dbConn.dbname,
        timeout: form.dbConn.timeout,
        isAutoMigrate: form.dbConn.isAutoMigrate,
      },
      redis: {
        addr: form.redis.addr,
        db: form.redis.db,
      },
    },
  })
  formData.value.securejsonData = JSON.stringify({ password: encryptByRsa(form.dbConn.password), redisPassword: encryptByRsa(form.redis.redis_password) })
  await UpdateDataSource(formData.value)
  await getDataList()
  Message.success('保存设置成功')
  // 检查健康状态
  const result = await CheckHealth('caipu-site')
  isAlert.value = true
  if (result.success) {
    isAlert.value = true
    alerttype.value = 'success'
    alertText.value = '配置成功'
  } else {
    alerttype.value = 'error'
    alertText.value = `配置失败，原因:${result.msg}`
  }
}

// 恢复默认
const handleResetValue = async () => {
  Message.success('恢复成功')
  await getDataList()
}
const onResetValue = () => {
  Modal.warning({
    title: '警告',
    content: '确认恢复配置为默认值吗？',
    hideCancel: false,
    maskClosable: false,
    onOk: handleResetValue,
  })
}

onMounted(() => {
  getDataList()
})
</script>

<style scoped lang="scss">
:deep(.arco-form-item.arco-form-item-has-help) {
  margin-bottom: 5px;
}

:deep(.form .arco-input-wrapper),
:deep(.arco-select-view-single) {
  width: 220px;
}
</style>
